package com.hzsai.controller;

import com.hzsai.pojo.User;
import com.hzsai.pojo.UserVO;
import com.hzsai.pojo.Validatorpojo;
import com.hzsai.service.PdfExportService;
import com.hzsai.service.UserService;
import com.hzsai.utils.ResponseMsg;
import com.hzsai.utils.ResultMsg;
import com.hzsai.view.PdfView;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.PdfCell;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "用户信息")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/insertUser")
    public ResponseMsg insertUser(String user, String pwd) {
        return userService.insertUser(user, pwd);
    }


    @PostMapping("/insertUserJson")
    public ResponseMsg insertUserJson(@RequestBody @Valid UserVO userVO) {
        User user = changToUser(userVO);
        return userService.insertUser(user);
    }

    @PostMapping("/findUsersByIds")
    ResultMsg findUsersByIds(@RequestParam List<Integer> ids) {
        return ResultMsg.success(userService.findUsersByIds(ids));
    }

    @ApiOperation(value = "查询所有用户")
    @GetMapping("/selectAllUser")
    public ResponseMsg selectAllUser() throws SQLException {
        System.out.println("selectAllUser");
        return ResponseMsg.success(userService.selectAllUser());
    }

    @ApiOperation(value = "发送数组测试")
    @GetMapping("/sendMulti")
    public Map<String, Object> sendMultiArgs(
            int[] intArr, long[] longArr, String[] strArr) {
        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("intArr", intArr);
        retMap.put("longArr", longArr);
        retMap.put("strArr", strArr);
        return retMap;
    }

    @ApiOperation(value = "Required测试")
    @GetMapping("/sendRequestParam")
    public Map<String, Object> sendRequestParam(
            @RequestParam int intArr,
            @RequestParam long longArr,
            @RequestParam(value = "dodobird", required = false, defaultValue = "I_m_a_fat_fat_bird") String str) {

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("intArr", intArr);
        retMap.put("longArr", longArr);
        retMap.put("str", str);

        return retMap;
    }

    @ApiOperation(value = "分页查询")
    @GetMapping("/selectPage/{current}/")
    public ResponseMsg selectPageData(@PathVariable long current, @RequestParam long size) throws SQLException {
        return ResponseMsg.success(userService.selectPageUser(current, size));
    }

    @ApiOperation(value = "自定义转换")
    @PostMapping("/converter")
    public ResponseMsg converterInsertUser(User user) {
        return ResponseMsg.success(user);
    }

    /**
     * localhost:8000/user/converterList?userList=hzsai_123456_23, hzs_1_1, hzsai_22_22222
     * @param userList
     * @return
     */
    @ApiOperation(value = "List自定义转换")
    @PostMapping("/converterList")
    public List<User> converterInsertUserList(List<User> userList) {
        return userList;
    }


    @ApiOperation(value = "测试jsr303")
    @GetMapping("/validateJsr")
    public Map<String, Object> jsr303Validator(@Valid @RequestBody Validatorpojo vp, Errors errors) {
        Map<String, Object> errMap = new HashMap<String, Object>();

        List<ObjectError> oes = errors.getAllErrors();
        for (ObjectError oe : oes) {
            String key = null;
            Object val = null;
            if (oe instanceof FieldError) {
                key = ((FieldError) oe).getField();
            } else {
                key = oe.getObjectName();
            }
            val = oe.getDefaultMessage();
            errMap.put(key, val);
        }

        return errMap;
    }

    @ApiOperation(value = "什么是modelAndView")
    @GetMapping("/getModelAndView")
    public ModelAndView getModelAndView(@RequestParam String id, @RequestParam String name) {
        ModelAndView view = new ModelAndView();
        view.addObject("id", id);
        view.addObject("name", name);
        view.setViewName("index");
        return view;
    }

    @ApiOperation(value = "导出pdf")
    @GetMapping("/exportPDF")
    public ModelAndView exportPDF(@RequestParam Long current, @RequestParam Long size) throws SQLException {
        List<User> users = userService.selectPageUser(current, size);
        View view = new PdfView(exportService());
        ModelAndView mv = new ModelAndView();
        mv.setView(view);
        mv.addObject("userList", users);
        return mv;
    }

    private PdfExportService exportService() {
        return (model, document, writer, request, response) -> {
            try {
                response.setCharacterEncoding("UTF-8");
                document.setPageSize(PageSize.A4);
                // title
                document.addTitle("用户信息列表");
                document.add(new Chunk('\n'));
                // column 4
                PdfPTable table = new PdfPTable(4);
                PdfPCell cell = null;
                Font f8 = new Font();
                f8.setColor(Color.BLACK);
                f8.setStyle(Font.BOLD);
                //id
                cell = new PdfPCell(new Paragraph("Id", f8));
                cell.setHorizontalAlignment(1);
                table.addCell(cell);
                //username
                cell = new PdfPCell(new Paragraph("姓名", f8));
                cell.setHorizontalAlignment(1);
                table.addCell(cell);
                //age
                cell = new PdfPCell(new Paragraph("年龄", f8));
                cell.setHorizontalAlignment(1);
                table.addCell(cell);
                //password
                cell = new PdfPCell(new Paragraph("密码", f8));
                cell.setHorizontalAlignment(1);
                table.addCell(cell);

                List<User> userList = (List) model.get("userList");
                for (User user : userList) {
                    document.add(new Chunk('\n'));
                    // id
                    cell = new PdfPCell(new Paragraph(user.getId().toString(), f8));
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                    //username
                    cell = new PdfPCell(new Paragraph(user.getUsername().toString(), f8));
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                    //age
                    cell = new PdfPCell(new Paragraph(String.valueOf(user.getAge()), f8));
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                    //password
                    cell = new PdfPCell(new Paragraph(user.getPassword().toString(), f8));
                    cell.setHorizontalAlignment(1);
                    table.addCell(cell);
                }
                document.add(table);
                f8.setSize(50);
                PdfPTable table_2 = new PdfPTable(1);
                PdfPCell cell1 = null;
                cell1 = new PdfPCell(new Paragraph("DODOBird", f8));
                cell1.setHorizontalAlignment(1);
                table_2.addCell(cell1);
                document.add(table_2);

            } catch (DocumentException e) {
                e.printStackTrace();
            }
        };
    }

    public static User changToUser(UserVO userVO) {
        User user = new User();
        user.setUsername(userVO.getUsername());
        user.setPassword(userVO.getPassword());
        user.setAge(userVO.getAge());

        return user;
    }
}
